import { useEffect } from 'react'
import { useSelector, useDispatch } from "react-redux";  
import { useNavigate, useLocation, matchRoutes } from "react-router-dom";  
import { routes } from "./index";
import '@/store/index.js'
import { fetchUser } from '@/store/modules/user.js'  
import { setMenu } from '@/store/modules/menu.js'  
const Guard = ({ children, auth }) => {  
  const navigate = useNavigate();  
  const dispatch = useDispatch();
  const user = useSelector((state) => state.user);  
  const location = useLocation();  
  useEffect(() => {  
    const {token, infoStatus, info} = user
    // 检查token，如果没有token且需要鉴权，则导航到登录页面  
    if ((token === "" || token === null) && auth) {
      navigate("/login");  
    }  
    // 如果已经登录，但是直接访问了登录页面，则导航到首页  
    const mathchs = matchRoutes(routes, location);  
    const isExist = mathchs?.some((item) => item.pathname === location.pathname);  
    if (token && isExist) { 
      if(location.pathname === "/" || location.pathname === "/login"){
        navigate("/home");
      }
      if(!info&&!infoStatus){
        dispatch(fetchUser())
        dispatch(setMenu())
      }
    }
  }, [user, location, auth, navigate, dispatch]); 
  
  // 组件渲染时，直接返回子组件  
  return children;  
};  
  
export default Guard;